<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;


class BusinessPlan extends Model
{

    

    

    // 表名
    protected $name = 'business_plan';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'apply_time_text',
        'start_time_text',
        'end_time_text',
	    'status_text',
	    'area_text'
    ];
    
	const STATUS_ING = 1;
	const STATUS_WAIT = 0;
	const STATUS_OVER = 2;
    
	public static $statusList = [
		self::STATUS_ING => '进行中',
		self::STATUS_WAIT => '报名中',
		self::STATUS_OVER => '已结束'
	];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? : $data['status'];
		$list = self::$statusList;
		return $list[$value] ?? '';
	}
	
	public function getAreaTextAttr($value, $data) {
		$value = $value ? : $data['area'];
		$list = \app\admin\model\User::$areaList;
		return $list[$value] ?? '';
	}

    public function getApplyTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['apply_time']) ? $data['apply_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setApplyTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setStartTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
	
	public function goods() {
		return $this->belongsTo('goods', 'goods_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function spec() {
		return $this->belongsTo('goodsSpec', 'spec_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	/**
	 * 检查当前订单推荐人是否加入了创业大赛
	 * @param $userId 订单推荐人
	 * @param $level 推荐人等级
	 * @param $area 订单区域
	 * @param $goodsId 商品ID
	 * @param $specId 规格ID
	 * @return array|bool|false|\PDOStatement|string|Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    public function checkUserJoinStatus($userId, $level, $area, $goodsId, $specId) {
    	$userModel = new \app\admin\model\User();
    	$levelList = [$userModel::LEVEL_PROMOTION, $userModel::LEVEL_WAREHOUSE, $userModel::LEVEL_SHOP];
    	if($area == $userModel::AREA_SZ) {
    	    $levelList[] = $userModel::LEVEL_CENTER;
	    }
    	
    	//没有资格参与大赛的直接是不参与
    	if(!in_array($level, $levelList)) {
    		return false;
	    }
    	
    	//查找正在进行中的大赛
	    $plan = Db::name('businessPlan')->where([
	    	'area' => $area,
		    'start_time' => ['elt', time()],
		    'end_time' => ['gt', time()]
	    ])->find();
    	
    	
    	if(!$plan || $plan['goods_id'] != $goodsId || $plan['spec_id'] != $specId) {
    		return false;
	    }
    	
    	//查找是否已经售完了
	    if($plan['sale_number'] >= $plan['number']) {
	    	return false;
	    }
	    
	    //深圳的场景店，查找他的发展中心
	    if($area == $userModel::AREA_SZ && $level == $userModel::LEVEL_SHOP) {
	    	$agent = AgentShop::get(['user_id' => $userId]);
	    	if($agent && $agent['recommend_user_id']) {
	    		$userId = $agent['recommend_user_id'];
		    }
	    }
	    
	    $member = Db::name('teamMember')->alias('m')
		    ->join('businessPlan p', 'm.business_plan_id = p.id', 'left')
		    ->where(['m.business_plan_id' => $plan['id'], 'm.user_id' => $userId])
		    ->field('m.id, m.team_id, m.business_plan_id, p.number, p.sale_number, m.user_id')
		    ->find();
	    
	    if($member) {
	    	return  $member;
	    } else {
	    	return false;
	    }
	    
    }
	
	/**
	 * 添加大赛销售数量
	 * @param $planId 活动ID
	 * @param $teamId 战队ID
	 * @param $memberId 战队成员ID
	 * @param $number 数量
	 * @param $allNumber 活动数量
	 * @param $saleNumber 已售数量
	 * @param $userId 销售用户
	 * @param $orderId 订单ID
	 * @return bool
	 */
    public function addSaleNumber($planId, $teamId, $memberId, $number, $allNumber, $saleNumber, $userId, $orderId) {
    	try {
    		//给自己加数量
		    $selfRes = Db::name('teamMember')->where(['id' => $memberId])->setInc('number', $number);
		    if(!$selfRes) {
		    	throw new Exception('添加自己大赛销量出错');
		    }
		    
		    //给团队加数量
		    $teamRes = Db::name('team')->where(['id' => $teamId])->setInc('number', $number);
		    if(!$teamRes) {
		    	throw new Exception('添加战队销量出错');
		    }
		    
		    //给活动加销量
		    $planRes = Db::name('BusinessPlan')->where(['id' => $planId])->setInc('sale_number', $number);
		    if(!$planRes) {
			    throw new Exception('添加大赛销量出错');
		    }
		    
		    if($saleNumber + $number >= $allNumber) {
			    $statusRes = Db::name('BusinessPlan')->where(['id' => $planId])->update(['status' => self::STATUS_OVER]);
			    if(!$statusRes) {
				    throw new Exception('更改大赛状态出错');
			    }
		    }
		    
		    $itemModel = new TeamSaleItem();
		    $itemRes = $itemModel->addNumber($planId, $teamId, $userId, $number, $orderId);
		    if(!$itemRes) {
		    	throw new Exception('添加战队销量明细出错');
		    }
    		return true;
	    } catch (Exception $e) {
    		$this->error = $e->getMessage();
    		return false;
	    }
    }

}
